<template>
  <div id="findClinic">
    <header>
      <i @click="goBack()"></i>
      <div>寻找诊室</div>
      <router-link :to='{name:"selectClinic",query: {user: "doctor",lng_lat: lng_lat, area: JSON.stringify(area)}}'>
              <img src="../../../image/trans.png" alt="">
        </router-link>
    </header>
    <!-- <div id='search_my'>
            <input type="text" @focus="showSearch = false" @blur='blurFun'>
        </div> -->
    <div>
      <div class='search'>
        <input type="text" id="suggestId" size="20" placeholder="请输入地址" @input='isShowX' v-model='inputVal'>
        <!-- <img v-if='showX' src="../../../image/icon_closed.png" width="20" height="20" alt="" @click='clearInput'> -->
        <span @click='goNext'>确定</span>
        <span @click='cancel'>取消</span>
        <!-- <span>搜索</span> -->
      </div>
      <div id="searchResultPanel"></div>
      <div id='allmap' @touchstart='blurInput'></div>
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        letter: '',
        inputVal: '',
        showX: false,
        // isFocus: true,  //是否可以聚焦于表单 默认是 当搜索完后否
        user: '',
        pointArr: [], //标记点诊室
        iconImg: require('../../../image/me.png'),
        lng_lat: '',
        area: {
          city: '',
          detailAddress: ''
        }
      }
    },
    methods: {
      // 选择后到诊室页面
      goNext() {
        $('.tangram-suggestion-main').hide();
        if (this.area.detailAddress == '') {
          this.area.detailAddress = this.inputVal
        }
        if (this.lng_lat && this.area.detailAddress) {
          this.$router.push({
            name: 'selectClinic',
            query: {
              lng_lat: this.lng_lat,
              user: 'doctor',
              area: JSON.stringify(this.area)
            }
          });
        } else {
          this.$utils._toast('请选择地址');
        }
      },
      // 取消
      cancel() {
        this.inputVal = '';
        this.area.detailAddress = '';
        this.lng_lat = '';
      },
      blurFun() {
        $('.tangram-suggestion-main').show();
      },
      //返回上一级
      goBack() {
        // this.$router.back();
        this.$router.push({
          name: "ImDoctor"
        });
        // if(this.$route.query.user == "patient") {
        //     this.$router.push({name: 'ImPatient'});
        // } else {
        //     this.$router.push({name: 'selectClinic',query:{user: 'doctor'}});
        // }
      },
      // 判断入口
      init() {
        if (this.$route.query.user) {
          this.user = this.$route.query.user;
        } else {
          this.user = "doctor";
        }
      },
      //显示清空的图标
      isShowX() {
        if (this.inputVal) {
          this.showX = true;
        } else {
          this.showX = false;
        }
      },
      //清空输入框
      clearInput() {
        this.inputVal = '';
      },
      // 让input失去焦点
      blurInput() {
        $("#suggestId").blur();
      },
      // 获取所有诊室
      getClinicList() {
        this.$api.get(this.$api.baseURLSchool, "selectdata2/view_clinic_user", {}, r => {
          if (r.data.ret == 1) {
            this.pointArr = r.data.info;
          }
        }, err => {
          console.log(err);
        })
      },
      //地图初始化
      initMap() {
        // 设置以用户位置 或搜索位置为中心 选定一个范围 显示范围内标记
        function setArea(point) {
          // 范围 --start
          function getSquareBounds(centerPoi, r) {
            var a = Math.sqrt(2) * r; //正方形边长  
            var mPoi = getMecator(centerPoi);
            var x0 = mPoi.x,
              y0 = mPoi.y;

            var x1 = x0 + a / 2,
              y1 = y0 + a / 2; //东北点  
            var x2 = x0 - a / 2,
              y2 = y0 - a / 2; //西南点  

            var ne = getPoi(new BMap.Pixel(x1, y1)),
              sw = getPoi(new BMap.Pixel(x2, y2));
            //限制区域
            return new BMap.Bounds(sw, ne);
          }


          //根据球面坐标获得平面坐标。  
          function getMecator(poi) {
            return map.getMapType().getProjection().lngLatToPoint(poi);
          }
          //根据平面坐标获得球面坐标。  
          function getPoi(mecator) {
            return map.getMapType().getProjection().pointToLngLat(mecator);
          }
          // --范围--end  //方圆200米
          var circle = new BMap.Circle(point, 1000, {
            strokeColor: "blue",
            strokeWeight: 2,
            strokeOpacity: 0.5,
            fillColor: ""
          });

          var bounds = getSquareBounds(circle.getCenter(), circle.getRadius());
          var timer = setTimeout(() => {
            if (_this.pointArr.length) {
              _this.pointArr.forEach((val, index) => {
                const lat_lng = val.lat_lng;
                if (lat_lng) {
                  var p0 = lat_lng.split(",")[1];
                  var p1 = lat_lng.split(",")[0];
                }
                const point = new BMap.Point(p0, p1); //循环生成新的地图点
                if (bounds.containsPoint(point)) {
                  var sContent = "<h3 style='margin:0 0 5px 0;padding:5px 0'>" + val.clinicname + "</h3>" +
                    "<img style='float:right;margin:2px' id='imgDemo' src='" + val.reportpic +
                    "' width='60' height='60' title='天安门'/>" +
                    // "<p style='margin:0;line-height:1.5;font-size:13px;'>联系方式: 13312341234</p>" +
                    "<p style='margin:0;line-height:1.5;font-size:13px;'>地址:" + val.address + "</p>" +
                    "</div>";
                  addMarker(point, sContent);
                }
              });
              clearInterval(timer);
            }
          }, 100);
          map.addOverlay(circle);
        }



        // 选择并点击下拉列表时触发
        function setPlace() {
          map.clearOverlays(); //清除地图上所有覆盖物

          function myFun() {
            var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果

            _this.lng_lat = JSON.stringify(pp);
            //矩形范围搜索
            map.centerAndZoom(pp, 18);
            var myIcon = new BMap.Icon(_this.iconImg, new BMap.Size(30, 30));
            var mk = new BMap.Marker(pp, {
              icon: myIcon
            });
            map.addOverlay(mk);
            setArea(pp);
          }

          var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
          });
          local.search(myValue);
        }



        var _this = this;
        var map = new BMap.Map('allmap'); //创建map实例
        var point = new BMap.Point(108.91388,34.240108);
        map.centerAndZoom(point, 18);

        // map.addEventListener("click", function (e) {
        //   alert(e.point.lng + "," + e.point.lat);
        // });

        // 编写自定义函数,创建标注
        function addMarker(point, content) {
          var marker = new BMap.Marker(point); //创建标注
          map.addOverlay(marker); // 将标注添加到地图中
          marker.addEventListener("click", function (e) {
            openInfo(content, e)
            alert(e.point.lng + ", " + e.point.lat);
          });
        }


        // Geolocation获取当前位置的经纬度
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.lng_lat = JSON.stringify(r.point);
            _this.area.city = r.address.city;
            //创建小狐狸
            var myIcon = new BMap.Icon(_this.iconImg, new BMap.Size(30, 30));
            var mk = new BMap.Marker(r.point, {
              icon: myIcon
            });
            map.addOverlay(mk);
            map.panTo(r.point);
           	
            setArea(r.point);
          } else {
            _this.$utils._toast('failed' + this.getStatus());
          }
        }, {
          enableHighAccuracy: true
        });

        //搜索关键词
        // 百度地图API功能
        function G(id) {
          return document.getElementById(id);
        }
        var ac = new BMap.Autocomplete( //建立一个自动完成的对象
          {
            "input": "suggestId",
            "location": map
          });
        ac.addEventListener("onhighlight", function (e) { //鼠标放在下拉列表上的事件
          var str = "";
          var _value = e.fromitem.value;
          var value = "";
          if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
          }
          str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

          value = "";
          if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
          }
          str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
          G("searchResultPanel").innerHTML = str;
        });
        var myValue;
        ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
          var _value = e.item.value;
          myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
          G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " +
            myValue;
          _this.area.city = _value.city;
          _this.area.detailAddress = myValue;
          setPlace();
        });

        function addClickHandler(content, marker) {
          marker.addEventListener("click", function (e) {
            openInfo(content, e)
          });
        }

        function openInfo(content, e) {
          var p = e.target;
          var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
          var infoWindow = new BMap.InfoWindow(content); // 创建信息窗口对象 
          map.openInfoWindow(infoWindow, point); //开启信息窗口
        }
        map.enableScrollWheelZoom(true); //启用滚轮放大缩小，默认禁用。
        map.enableDoubleClickZoom(true); //启用双击放大，默认启用。
        map.enablePinchToZoom(true); //启用双指操作缩放，默认启用。
      },
    },
    mounted() {
      this.init();
      this.getClinicList();
      this.initMap();
    },
    created() {

    }
  }

</script>
<style lang="scss" scoped>


</style>
